package com.itheima.tilas.Utils;

import com.aliyun.core.utils.StringUtils;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.itheima.tilas.config.AliyunOssConfig;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Objects;
import java.util.UUID;

/**
 * oss文件上传工具类
 *
 * @author 123
 */

public class OssUtil {

    private OssUtil() {
    }

    public static String aliyunFileUploadingUrl(MultipartFile file, AliyunOssConfig ossConfig) {

        //拆分文件后缀(类型)
        String filename = file.getOriginalFilename();
        if (StringUtils.isEmpty(filename)) {
            return null;
        }
        String suffix = filename.substring(filename.indexOf("."));
        //阿里云oss访问路径
        String endpoint = ossConfig.getEndpoint();
        // 填写Bucket名称，例如zmf-test-java。
        String bucketName = ossConfig.getBucketName();
        //生成不重复的id
        String uuid = UUID.randomUUID().toString();
        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
        String objectName = uuid + suffix;
        //转移文件到阿里云
        // 创建OSSClient实例,要指定访问对象。
        OSS ossClient = new OSSClientBuilder().build(endpoint,
                ossConfig.getAccessKeyId(), ossConfig.getSecretAccessKey());
        try {
            ossClient.putObject(bucketName, objectName, file.getInputStream());
            return ossConfig.getUrl() + objectName;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }
}
